package com.apestech.api.xml.esb;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.FileUtil;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.util.StringUtil;
import com.apestech.framework.xml.ReadXmlNodeInter;
import com.apestech.framework.xml.plugin.XmlIdVar;
import com.apestech.framework.xml.plugin.modul.SysCondition;
import com.apestech.framework.xml.table.modul.Tables;
import org.dom4j.Element;

import java.io.File;
import java.util.ArrayList;

/**
 * @author hup
 * @create 2019-11-25-17:10
 */
public class EsbUtil extends StringUtil {
    private static JSONObject formType=new JSONObject();
    private static JSONObject gridType=new JSONObject();
    private static JSONObject defaultValue=new JSONObject();
    private static String formT="";
    private static String gridT="";

    private static JSONObject formDef=new JSONObject();
    private static JSONObject divDef=new JSONObject();

    private static JSONObject downData=new JSONObject();
    private static JSONObject popform=new JSONObject();
    private static JSONObject formCondition=new JSONObject();

    private static JSONObject fieldChange=new JSONObject();
    private static JSONObject fieldDef=new JSONObject();
    private static JSONObject fieldD=new JSONObject();

    private static JSONObject seqmap=new JSONObject();

    public static void getAllField() throws Exception {
        String path=LocalVariable.getRootDir()+"condition"+ File.separator +"esb"+ File.separator +"esb_field.xml";
        XmlPasteEsb xml=new XmlPasteEsb("fieldDef", path, XmlIdVar.STR_TYPE.FILE_PATH);
        xml.expain();
        JSONObject modul=xml.getResultSingle();
        JSONObject form= (JSONObject) modul.get("form");
        formT=form.getString("type");
        form.remove("type");
        JSONObject grid= (JSONObject) modul.get("grid");
        gridT=grid.getString("type");
        grid.remove("type");
        ArrayList<String> klist=form.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            addFormType((JSONObject) form.get(klist.get(i)), null);
        }
        klist=grid.getKeylist();
        len=klist.size();
        for(int i=0; i<len; i++){
            addGridType((JSONObject) grid.get(klist.get(i)), null);
        }
        xml.getNodeNameJson("default");
        modul=xml.getResultSingle();
        addFormField(modul);

        xml.getNodeNameJson("formDef");
        modul=xml.getResultSingle();
        klist=modul.getKeylist();
        len=klist.size();
        for(int i=0; i<len; i++){
            addFormDef((JSONObject) modul.get(klist.get(i)), null);
        }
        xml.getNodeNameJson("divDef");
        modul=xml.getResultSingle();
        klist=modul.getKeylist();
        len=klist.size();
        for(int i=0; i<len; i++){
            addDivDef((JSONObject) modul.get(klist.get(i)), null);
        }

        xml.getNodeNameJson("fieldChange");
        fieldChange=xml.getResultSingle();

        xml.getNodeNameJson("fieldDef");
        fieldDef=xml.getResultSingle();

        xml.getNodeNameJson("fieldD");
        fieldD=xml.getResultSingle();
    }

    public static String getFieldChange(String field) throws Exception {
        return fieldChange.getString(field);
    }

    public static String getfieldDef(String field) throws Exception {
        return fieldDef.getString(field);
    }

    public static JSONObject getfieldD(String field) throws Exception {
        return (JSONObject) fieldD.get(field);
    }

    public static void addFormType(JSONObject input, String theme) throws Exception {
        String type=input.getString(formT);
        if(type==null) type="f_pub";
        String id=type;
        if(theme!=null) id=theme+"."+id;
        formType.put(id, input);
    }

    public static JSONObject getFormType(String type, String theme){
        String id=type;
        if(theme!=null) id=theme+"."+id;
        Object obj=formType.get("F_"+id);
        if(obj==null){
            if(type!=null){
                JSONObject m= (JSONObject) formType.get("F_"+id);
                if(m==null) m= (JSONObject) formType.get(type);
                if(m==null) m=new JSONObject();
                String pub=m.getString("pub");
                JSONObject map=new JSONObject();
                if(!"false".equals(pub)){
                    map.putAllDetail((JSONObject) formType.get("f_pub"));
                }
                if(m!=null) map.putAllDetail(m);
                obj=map;
                formType.put("F_"+id, map);
            } else {
                return (JSONObject) formType.get("f_pub");
            }
        }
        return (JSONObject) obj;
    }

    public static void addGridType(JSONObject input, String theme) throws Exception {
        String type=input.getString(gridT);
        if(type==null) type="f_pub";
        String id=type;
        if(theme!=null) id=theme+"."+id;
        gridType.put(id, input);
    }

    public static JSONObject getGridType(String type, String theme){
        String id=type;
        if(theme!=null) id=theme+"."+id;
        Object obj=gridType.get("F_"+id);
        if(obj==null){
            JSONObject m= (JSONObject) gridType.get(id);
            if(m==null) m= (JSONObject) gridType.get(type);
            JSONObject map=new JSONObject();
            map.putAllDetail((JSONObject) gridType.get("f_pub"));
            if(m!=null) map.putAllDetail(m);
            obj=map;
            gridType.put("F_"+id, map);
        }
        return (JSONObject) obj;
    }

    public static void addFormField(JSONObject param){
        if(param==null) return;
        defaultValue.putAll(param);
    }

    public static String getFormField(String id, String theme){
        String sid=id;
        if(theme!=null) sid=theme+"."+sid;
        String s=defaultValue.getString(sid);
        if(s==null) return defaultValue.getString(id);
        return s;
    }

    public static void addFormDef(JSONObject input, String theme) throws Exception {
        String type=input.getString("type");
        if(type==null) type="f_pub";
        String id=type;
        if(theme!=null) id=theme+"."+id;
        if("tab".equals(type)) input.remove("type");
        formDef.put(id, input);
    }

    public static JSONObject getFormDef(String type, String theme){
        String id=type;
        if(theme!=null) id=theme+"."+id;
        Object obj=formDef.get("F_"+id);
        if(obj==null){
            JSONObject m= (JSONObject) formDef.get(id);
            if(m==null) m= (JSONObject) formDef.get(type);
            JSONObject map=new JSONObject();
            if(m!=null) map.putAllDetail(m);
            obj=map;
            formDef.put("F_"+id, map);
        }
        return (JSONObject) obj;
    }

    public static void addDivDef(JSONObject input, String theme) throws Exception {
        String type=input.getString("type");
        String id=type;
        if(theme!=null) id=id+"."+theme;
        divDef.put(id, input);
    }

    public static JSONObject getDivDef(String type, String theme){
        String id=type;
        if(theme!=null) id=theme+"."+id;
        Object obj=divDef.get("F_"+id);
        if(obj==null){
            JSONObject m= (JSONObject) divDef.get(id);
            if(m==null) m= (JSONObject) divDef.get(type);
            JSONObject map=new JSONObject();
            //map.putAllDetail((JSONObject) divDef.get("f_pub"));
            if(m!=null) map.putAllDetail(m);
            obj=map;
            divDef.put("F_"+id, map);
        }
        return (JSONObject) obj;
    }

    public static void setDownData(String field, ArrayList<ArrayList<String>> list){
        JSONArray out=new JSONArray();
        int len=list.size();
        if(len<2) return;
        for(int i=0; i<len; i++){
            ArrayList<String> item=list.get(i);
            JSONObject map=new JSONObject();
            map.put("id", item.get(0));
            map.put("name", item.get(1));
            out.add(map);
        }
        downData.put(field, out);
    }

    public static JSONArray getDownData(String field){
        return (JSONArray) downData.get(field);
    }

    public static JSONObject getDownData(String field, String value){
        if(field.equals("STATE") && downData.get("STATE")==null){
            JSONArray item=new JSONArray();
            JSONObject map=new JSONObject();
            map.put("id", "sent");
            map.put("name", "新建");
            item.add(map);
            map=new JSONObject();
            map.put("id", "exec");
            map.put("name", "执行");
            item.add(map);
            map=new JSONObject();
            map.put("id", "stop");
            map.put("name", "终止");
            item.add(map);
            downData.put("STATE", item);
        }
        JSONArray list=(JSONArray) downData.get(field);
        if(list==null) return null;
        JSONObject m=null;
        int len=list.size();
        for(int i=0; i<len; i++){
            if(value.equals(list.get(i).getString("id"))){
                m=list.get(i);
                break;
            }
        }
        return m;
    }

    public static void getAllPop() throws Exception {
        String path=LocalVariable.getRootDir()+"config"+File.separator+"dyform"+File.separator;
        if(FileUtil.isFileExist(path+"esb")){
            path=path+"esb"+File.separator;
        }
        XmlPasteEsb xmlp=new XmlPasteEsb();
        xmlp.getXmlQuery().setFileDir(path);
        ArrayList<String> nlist=new ArrayList<String>();
        nlist.add("form");
        nlist.add("formCondition");
        xmlp.getXmlQuery().getXmlFileNode(nlist, new ReadXmlNodeInter(){
            @Override
            public void ReadNode(Element root, Element node, String nodename) throws Exception {
                String id=node.attributeValue("id");
                xmlp.expain(root, node);
                switch (nodename){
                    case "form":{
                        JSONObject modul=xmlp.getResultSingle();
                        popform.put(id, modul);
                        break;
                    }
                    case "formCondition":{
                        JSONObject modul=xmlp.getResultSingle();
                        formCondition.put(id, modul);
                        break;
                    }
                }
            }
        });
    }

    public static void reloadFormXml(String file) throws Exception {
        String path=LocalVariable.getRootDir()+"config"+File.separator+"dyform"+File.separator;
        if(FileUtil.isFileExist(path+"esb")){
            path=path+"esb"+File.separator;
        }
        if(file.indexOf(path)<0) return;
        XmlPasteEsb xmlp=new XmlPasteEsb();
        xmlp.getXmlQuery().setFileDir(file);
        ArrayList<String> nlist=new ArrayList<String>();
        nlist.add("form");
        nlist.add("formCondition");
        xmlp.getXmlQuery().getXmlFileNode(nlist, new ReadXmlNodeInter(){
            @Override
            public void ReadNode(Element root, Element node, String nodename) throws Exception {
                String id=node.attributeValue("id");
                xmlp.expain(root, node);
                switch (nodename){
                    case "form":{
                        JSONObject modul=xmlp.getResultSingle();
                        popform.put(id, modul);
                        break;
                    }
                    case "formCondition":{
                        JSONObject modul=xmlp.getResultSingle();
                        formCondition.put(id, modul);
                        break;
                    }
                }
            }
        });
    }

    public static JSONObject getPop(String id){
        Object p=popform.get(id);
        if(p==null) return null;
        return (JSONObject) p;
    }

    public static JSONObject getFormCondition(String id){
        Object p=formCondition.get(id);
        if(p==null) return null;
        return (JSONObject) p;
    }

    public static JSONObject getTableIsField(Tables tabs){
        JSONObject map=new JSONObject();
        ArrayList<String> klist=tabs.getKeylist();
        int len=klist.size();
        for(int i=0;i<len;i++){
            Tables.Table tab=tabs.getTable(klist.get(i));
            ArrayList<Tables.Field> flist=tab.getFields();
            String field="";
            int flen=flist.size();
            for(int f=0;f<flen;f++){
                Tables.Field fie=flist.get(f);
                if("NUMBER(1)".equals(fie.getType())){
                    String comm=fie.getComment();
                    if(comm.indexOf(")")<0 && comm.indexOf("）")<0 && comm.indexOf("(")<0 && comm.indexOf("（")<0){
                        if(!"".equals(field)) field=field+",";
                        field=field+fie.getId();
                    }
                }
            }
            if(!"".equals(field)){
                map.put(tab.getTabName(), field);
            }
        }
        return map;
    }

    public static JSONObject getConData(JSONObject map, SqlSession session, SysCondition sysCondition) throws Exception {
        if(map==null) return null;
        ArrayList<String> klist=map.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            String k=klist.get(i);
            Object value=map.get(k);
            if(value==null) {
                continue;
            }
            //PRODUCT_ID_CLASSIFY_ID
            if(klist.contains(k+"_NAME") || klist.contains(k+"_DESCRIPTION")){
                JSONObject m1=new JSONObject();
                m1.put("ID", map.get(k));
                if(klist.contains(k+"_NAME")){
                    m1.put("NAME",map.get(k+"_NAME"));
                    map.put(k, m1);
                    map.remove(k+"_NAME");
                } else {
                    m1.put("DESCRIPTION",map.get(k+"_DESCRIPTION"));
                    map.put(k, m1);
                    map.remove(k+"_DESCRIPTION");
                }

            } else {
                JSONObject m=sysCondition.getDimensionField(session.getTheme()+"."+k);
                if(m!=null){
                    String auxiliaryField=m.getString("auxiliaryField");
                    if(auxiliaryField!=null){
                        int pos=auxiliaryField.indexOf(",");
                        if(pos>=0){
                            auxiliaryField=auxiliaryField.substring(0, pos).trim();
                        }
                        JSONObject m1=new JSONObject();
                        m1.put("ID", map.get(k));
                        m1.put(auxiliaryField,map.get(k+"_"+auxiliaryField));
                        map.put(k, m1);
                        map.remove(k+"_"+auxiliaryField);
                    } else {
                        JSONObject v=getDownData(k, castToString(value));
                        if(v!=null){
                            map.put(k, v);
                        }
                    }
                } else {
                    JSONObject v=getDownData(k, castToString(value));
                    if(v!=null){
                        map.put(k, v);
                    }
                }
            }
        }
        return map;
    }

    public static JSONObject getSeqmap() {
        return seqmap;
    }

    public static void setSeqmap(JSONObject seqmap) {
        EsbUtil.seqmap = seqmap;
    }
}
